//
//  SJPhotoViewCell.swift
//  SJWeiboSwift
//
//  Created by app;e on 15/10/9.
//  Copyright © 2015年 world. All rights reserved.
//
//  点击cell中照片跳转的控制的  cell

import UIKit
import SDWebImage

protocol SJPhotoViewCellImageDelegate:NSObjectProtocol{
    //图片被点击
    func photoViewCellImageDidClick()
    //图片被缩放
    func photoViewDidScale(scale:CGFloat)
    //照片视图完成缩放
    func photoViewDidFinshScale()
}

class SJPhotoViewCell: UICollectionViewCell,UIScrollViewDelegate {
   
    //frame 已经有正确的数值, 是因为之前 在准备layout的时候
    //已经设置了itemSize
    override init(frame: CGRect) {
        super.init(frame: frame)
        scrollView.backgroundColor = UIColor.clearColor()
        scrollView.frame = UIScreen.mainScreen().bounds
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2
        addSubview(scrollView)
        scrollView.addSubview(imageView)
        
        //给imageView添加手势
        imageView.userInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: "imageDidClik")
        imageView.addGestureRecognizer(tap)
        
        addSubview(indicator)
        indicator.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: nil)
      
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //手势
    func imageDidClik(){
//        print(__FUNCTION__)
        //通知代理
        self.photoDelegate?.photoViewCellImageDidClick()
    }
    
    var imageURL: NSURL? {
        didSet{
            
           
            //重置scrollView的属性
            resetScrollView()
            
            //开始加载的时候转菊花
            indicator.startAnimating()
            
            //这种方法设置的imageView图片不会显示
            //因为imageView没有设置大小, 异步下载图片后 图片没办法显示
//            imageView.sd_setImageWithURL(imageURL)
            imageView.sd_setImageWithURL(imageURL, placeholderImage: nil) { (image, error, _, _ ) -> Void in
                //图片缓存完成,按照图片大小自适应imageView的大小
//                self.imageView.sizeToFit()
                //图片加载完成 停止
                self.indicator.stopAnimating()
                if image != nil{
                    self.imagePosition(image)
                }
            }
        }
    }
    
    //
    private func resetScrollView(){
        //cell在重用的时候可能会出问题,cell就只有2个,第三个在重用第一个cell的时候,里面scrollView的属性也会被重用,所以需要重置contentInSet等属性
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    //长短图的处理,返回图片位置
    func imagePosition(image:UIImage){
        
        //长图
        if bounds.height < image.size.height {
            imageView.frame = CGRect(origin: CGPointZero, size: image.size)
            scrollView.contentSize = image.size
        }else {
            let size = displaySize(image)
            //使用frame固定了imageView的的位置,当在进行缩放的时候,由于y值固定了,这个是时候缩放后imageView的y值也是固定了, 如果是段图,这样imageView上方的间距就没办法修改
            //所以该用contentInSet来设置
            let y = (bounds.height - size.height) * 0.5
//            imageView.frame = CGRect(origin: CGPoint(x: 0, y: y), size: size)
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentInset = UIEdgeInsetsMake(y, 0, 0, 0)
        }
        
    }
    
    //根据图片尺寸,等比例缩放,让图片能完全显示
    func displaySize(image:UIImage)->CGSize{
        let size = image.size
        let h = scrollView.frame.size.width * size.height / size.width
        return CGSize(width: scrollView.frame.size.width, height: h)
    }
    
    
    // MARK: - scrollView的代理
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    // 缩放过程中会一直调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
        /*
        public struct CGAffineTransform {
        public var a: CGFloat :缩放
        public var b: CGFloat
        public var c: CGFloat
        public var d: CGFloat :缩放
        public var tx: CGFloat :位移
        public var ty: CGFloat :位移
        */
        //CGAffineTransform(a: 1.09797845518782, b: 0.0, c: 0.0, d: 1.09797845518782, tx: 0.0, ty: 0.0)
//        print(imageView.transform)
        photoDelegate?.photoViewDidScale(imageView.transform.a)
        
    }
    // 缩放完成后会调用一次
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        print(__FUNCTION__)
        
        //scale < 0.8 直接 解除动画 不需要在调整
        if scale > 0.8 {
            var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
            //如果offsetY<0 的时候,也就是图片缩放以后 高度比屏幕要高 如果还设置偏移量,那么图片就不能图片上方的一部分了,所以如果小于0,将偏移量设置为0
            if offsetY < 0 {
                offsetY = 0
            }
            
            var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
            if offsetX < 0 {
                offsetX = 0
            }
            
            scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, 0, 0)

        }
        
        //通知代理完成缩放
        photoDelegate?.photoViewDidFinshScale()
        
    }
    
    //代理
    weak var photoDelegate:SJPhotoViewCellImageDelegate?
    
    //MARK: -懒加载子控件
    lazy var scrollView = UIScrollView()
    lazy var imageView = UIImageView()
   
    lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)

}
